using Tools;
using UnityEngine;

public class PlayerCameraLocator : VirtualCameraController
{
    private PlayerEntity playerEntity;
    private MoveAlongPathComponent moveAlongPathComponent;
    
    private Vector3 CurrentDirection
    {
        get
        {
            if (moveAlongPathComponent.currentEdge == null)
                return Vector3.right;
            Vector3 ret = moveAlongPathComponent.currentEdge.Direction;
            ret = new Vector3(ret.x, 0f, ret.z);
            return ret;
        }
    }

    [SerializeField]
    [Range(0f,90f)]
    private float defaultRotateSpeed;

    protected override void Awake()
    {
        base.Awake();
        playerEntity = PlayerEntity.Instance;
        moveAlongPathComponent = playerEntity.MoveAlongPathComponent;
    }
    private void FixedUpdate()
    {
        Synchronize(playerEntity.transform.position, CurrentDirection);
    }

    private void Synchronize(Vector3 position, Vector3 lookDireciton)
    {
        transform.position = position;

        Quaternion q = Quaternion.FromToRotation(transform.TransformDirection(Vector3.right), lookDireciton);
        q.ToAngleAxis(out float delta, out Vector3 axis);

        float abs = Mathf.Abs(delta);
        float rotateAngle = Mathf.Min(abs, CalculateRotateSpeed(abs) * Time.fixedDeltaTime);
        rotateAngle *= Mathf.Sign(delta);

        transform.Rotate(axis, rotateAngle);
    }

    private float CalculateRotateSpeed(float delta)
    {
        float ik = Mathf.Clamp01(Mathf.Abs(delta / 60f));
        float k = MathTool.PLerp(0.01f, 1f, ik, 2f);
        return k * defaultRotateSpeed;
    }

    private void OnDrawGizmos()
    {
        if(!Application.isPlaying)
        {
            transform.SetPositionAndRotation(PlayerEntity.Instance.transform.position, PlayerEntity.Instance.transform.rotation);
        }
    }
}
